from sqlalchemy.orm import Session
from typing import Union, Optional, Tuple, Type
from schemas.customer import CreateCustomerRequest, UpdateCustomerInfoRequest
from db import models


class Customer:
    @staticmethod
    def create(db: Session, data: CreateCustomerRequest) -> models.Customer:
        item = models.Customer(
            created_on=data.created_on,
            created_by=data.created_by,
            openid=data.openid,
            nickname=data.nickname,
            avatar=data.avatar,
            phone=data.phone,
            gender=data.gender
        )
        db.add(item)
        db.commit()
        return item

    @staticmethod
    def get_by_openid(db: Session, openid: str) -> Union[models.Customer, None]:
        return db.query(models.Customer).filter_by(openid=openid).first()

    @staticmethod
    def get(db: Session, id_: int) -> Union[models.Customer, None]:
        return db.query(models.Customer).get(id_)

    @staticmethod
    def gets(db: Session,
             page: int,
             page_size: int,
             kw: Optional[str] = None) -> Tuple[int, list[Type[models.Customer]]]:
        if kw is None:
            count = db.query(models.Customer).filter_by(status=1).count()

            data = db.query(models.Customer).filter_by(status=1).offset(page * page_size).limit(page_size).all()
        else:
            count = db.query(models.Customer).filter_by(status=1).filter(
                models.Customer.nickname.like(f"%{kw}%")).count()

            data = db.query(models.Customer).filter_by(status=1).filter(
                models.Customer.nickname.like(f"%{kw}%")).offset(page * page_size).limit(page_size).all()
        return count, data

    @staticmethod
    def update_info(db: Session, data: UpdateCustomerInfoRequest) -> Union[models.Customer, None]:
        print(data)
        item = db.query(models.Customer).get(data.id)
        if item is not None:
            if data.updated_by is not None:
                item.updated_by = data.updated_by

            if data.updated_on is not None:
                item.updated_on = data.updated_on

            if data.nickname is not None:
                item.nickname = data.nickname

            if data.avatar is not None:
                item.avatar = data.avatar

            if data.phone is not None:
                item.phone = data.phone

            if data.gender is not None:
                item.gender = data.gender

            db.commit()
            return item
